<template>
    <div>
<!--      面包屑导航-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
<!--  卡片视图区域-->
    <el-card class="box-card">

      <!--      搜索区域-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable
          @clear="getUserList" @change="getUserList" >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

<!--        用户列表区-->
      <el-table :data="userList" border stripe>
<!--          索引列-->
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column prop="username" label="用户名"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column label="用户状态">
<!--            作用域插槽 会覆盖prop属性，所以可以删除prop属性-->
            <template slot-scope="scope">
<!--              {{scope.row}}  这一行对应的所有数据-->
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="usersStateChange(scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <!--            作用域插槽-->
            <template slot-scope="scope">
<!--             修改按钮-->
<!--              open-delay延迟出现，单位毫秒 enterable 鼠标是否可进入到 tooltip 中-->
              <el-tooltip effect="dark" content="修改用户" placement="top" :open-delay=openDelay :enterable="false">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
              </el-tooltip>
<!--              删除按钮-->
              <el-tooltip effect="dark" content="删除用户" placement="top" :open-delay=openDelay :enterable="false">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="showDeltDialog(scope.row.id)"></el-button>
              </el-tooltip>
<!--              分配角色按钮-->
              <el-tooltip effect="dark" content="分配角色" placement="top" :open-delay=openDelay :enterable="false">
                <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

<!--      分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

<!--      添加用户弹框-->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="resetForm('addFormRef')">
        <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
        <el-button type="info" @click="resetForm('addFormRef')">重置</el-button>
        </span>
      </el-dialog>

      <!--      修改用户弹框-->
      <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="resetForm('editFormRef')">
        <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
        <el-button type="info" @click="resetForm('editFormRef')">重置</el-button>
        </span>
      </el-dialog>

      <!--     分配角色弹框-->
      <el-dialog
        title="分配角色"
        :visible.sync="setRoleDialogVisible"
        width="50%">
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
<!--          角色选择框-->
        <p>
          <span>分配新角色：</span>
          <el-select v-model="roleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>

        <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveSetRole">确 定</el-button>
        </span>
      </el-dialog>

    </div>
</template>

<style scoped>
    body {
        background-color: #ff0000;
    }
</style>

<script>
export default {
  data () {
    // 自定义校手机号验规则
    var checkPhone = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regPhone = /^1[3|4|5|7|8][0-9]{9}$/
      if (regPhone.test(value)) {
        // 手机号合法
        callback()
      } else {
        callback(new Error('请输入合法的手机号'))
      }
    }
    // 自定义校验邮箱规则
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/
      if (regEmail.test(value)) {
        // 邮箱合法
        callback()
      } else {
        callback(new Error('请输入合法的邮箱'))
      }
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 文字提示信息展示时间
      openDelay: 500,
      //  添加用户弹框开关
      addDialogVisible: false,
      // 修改用户开关
      editDialogVisible: false,
      // 分配角色开关
      setRoleDialogVisible: false,
      // 需要被分配权限的用户信息
      userInfo: {},
      // 所有角色信息
      roleList: [],
      // 将要分配角色ID
      roleId: '',
      //  添加用户的数据对象
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改用户表单数据
      editForm: {
        username: '',
        email: '',
        mobile: '',
        id: ''
      },
      //  添加表单的验证规则对象
      addRules: {
        username: [
          {
            required: true,
            message: '请输入登录用户名',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入登录密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: checkPhone,
            trigger: 'blur'
          }
        ]
      },
      //  修改用户规则
      editRules: {
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: checkPhone,
            trigger: 'blur'
          }
        ]
      }

    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
    },
    //  监听pageSize改变事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    //  监听页码值改变事件
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听Switch状态的改变
    async usersStateChange (userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 表单重置功能
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 添加用户功能
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        //  隐藏添加对话框
        this.addDialogVisible = false
        this.$message.success('添加成功')
        //  刷新列表
        this.getUserList()
      })
    },
    //  弹出修改用户对话框
    async showEditDialog (id) {
      //  根据id查询用户信息
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户数据失败')
      } else {
        this.editForm = res.data
        this.editDialogVisible = true
      }
    },
    editUser () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('更新用户失败')
        //  隐藏添加对话框
        this.editDialogVisible = false
        //  刷新列表
        this.getUserList()
        this.$message.success('更新用户成功')
      })
    },
    async deleteUser (id) {
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
    },
    // 删除弹框
    showDeltDialog (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteUser(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        //  刷新列表
        this.getUserList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    //  分配角色
    async setRole(userInfo) {
      this.setRoleDialogVisible = true
      // 获取所有角色信息
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.roleList = res.data
      console.log(this.roleList)
      // 用户信息
      this.userInfo = userInfo
    },
    // 提交分配角色
    async saveSetRole() {
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.roleId })
      if (res.meta.status !== 200) return this.$message.error('修改角色失败')
      //  刷新列表
      this.getUserList()
      //  清空相关数据
      this.roleId = ''
      //  关闭窗口
      this.setRoleDialogVisible = false
      return this.$message.success(res.meta.msg)
    }
  }
}
</script>
